﻿using AuthorityManagement.Helper;
using AuthorityManagement.Model;
using AuthorityManagement.Model.Dto;
using AuthorityManagement.Model.Dto.FileDto;
using AutoMapper;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using static AuthorityManagement.Helper.RuturnHelper;
using File = AuthorityManagement.Model.File;

namespace AuthorityManagement.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        private readonly ISqlSugarClient _Db;
        private IMapper _mapper;
        // 配置允许的最大文件大小等选项
        private readonly long _allowedFileSize = 10 * 1024 * 1024; // 10 MB
        public FilesController(ISqlSugarClient db, IMapper mapper)
        {
            _Db = db;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetFileId")]
        public async Task<dynamic>GetFileId(string id)
        {
            var data = await _Db.Queryable<File>().Where(it => it.Id == id).Select(it => new FileListOutput() { Id = it.Id, Type = it.Type, Remark = it.Remark, fileJson = it.FileInfo, }).Mapper(it => { it.FileInfo = JsonConvert.DeserializeObject<List<FileControlsModel>>(it.fileJson); it.FileInfoJosn = string.Join("；", it.FileInfo.Select(s => s.name)); }).FirstAsync();
            return data;
        }
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns> 
        [HttpGet("")]
        public async Task<dynamic> GetFileList(/*[FromBody] FileCrInput input*/)
        {
            var data = await _Db.Queryable<File>().Where(it => it.DeletedMark == null).Select(it => new FileListOutput { Id = it.Id, Type = it.Type, Remark = it.Remark, fileJson = it.FileInfo }).Mapper(it => { it.FileInfo = JsonConvert.DeserializeObject<List<FileControlsModel>>(it.fileJson); it.FileInfoJosn = string.Join("；", it.FileInfo.Select(s => s.name)); }).ToListAsync();
            return data;
        }

        /// <summary>
        /// 新增文件
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("Create")]
        public async Task<dynamic> Create([FromBody] FileCrInput input)
        {
            var data = input.Adapt<File>();
            data.Id = Guid.NewGuid().ToString("N");
            data.FileInfo = data.FileInfo.ToJson();
            var isOk = await _Db.Insertable(data).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0))
            {
                return RR.Error("新增失败!");
            }
            else
            {
                return RR.Success("新增成功！");
            }
        }

        /// <summary>
        /// 修改文件
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("Update")]
        public async Task<dynamic> Update(string id, [FromBody] FileUpInput input)
        {
            var data = input.Adapt<File>();
            data.FileInfo= input.FileInfo.ToJson();
            var isOk = await _Db.Updateable(data).UpdateColumns(it => new  { it.Id, it.Type,  it.Remark,  it.FileInfo }).ExecuteCommandAsync();
            if (!(isOk > 0))
            {
                return RR.Error("编辑失败!");
            }
            else
            {
                return RR.Success("编辑成功！");
            }

        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("Delete")]
        public async Task<dynamic> Delete(string id)
        {
            var data = await _Db.Deleteable<File>().Where(it => it.Id == id).ExecuteCommandAsync();
            if (data > 0)
            {
                return RR.Success("删除成功");
            }
            else
            {
                return RR.Error("删除失败！");
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        [HttpPost("FileUpload")]
        public async Task<dynamic> FileUpload(IFormFile formFile)
        {
            var currentDate = DateTime.Now;
            var webRootPath = $"D:/qxAPI/Test/TemplateFile";//>>>相当于HttpContext.Current.Server.MapPath("") 

            try
            {
                var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";

                //创建每日存储文件夹
                if (!Directory.Exists(webRootPath + filePath))
                {
                    Directory.CreateDirectory(webRootPath + filePath);
                }

                if (formFile != null)
                {
                    //文件后缀
                    var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式，拓展名

                    //判断文件大小
                    var fileSize = formFile.Length;

                    if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
                    {
                        return new JsonResult(new { isSuccess = false, resultMsg = "上传的文件不能大于10M" });
                    }

                    //保存的文件名称(以名称和保存时间命名)
                    var saveName = formFile.FileName.Substring(0, formFile.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;

                    //文件保存
                    using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
                    {
                        formFile.CopyTo(fs);
                        fs.Flush();
                    }

                    //完整的文件路径
                    var completeFilePath = Path.Combine(filePath, saveName);
                    FileSaveURL filesaveurl = new FileSaveURL()
                    {
                        Id = SnowFlakeSingle.Instance.NextId().ToString("N"),
                        URL = completeFilePath,
                        Remark = "",
                    };
                    return new JsonResult(new { isSuccess = true, returnMsg = "上传成功", completeFilePath = completeFilePath });
                }
                else
                {
                    return new JsonResult(new { isSuccess = false, resultMsg = "上传失败，未检测上传的文件信息~" });
                }

            }
            catch (Exception ex)
            {
                return new JsonResult(new { isSuccess = false, resultMsg = "文件保存失败，异常信息为：" + ex.Message });
            }

        }

        /// <summary>
        /// 上传文件.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("Uploader")]
        [AllowAnonymous]
        public async Task<dynamic> Uploader(IFormFile file)
        {
            //调用文件上传的接口 把文件上传到指定位置 返回文件名和路径 到时候预览或者下载的时候直接指定url进行下载
            if (file == null || file.Length == 0)
                return BadRequest("No file uploaded.");

            if (file.Length > _allowedFileSize)
                return BadRequest("File size exceeds the allowed limit.");

            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "UploadedFiles", file.FileName);

            // 确保上传文件夹存在
            Directory.CreateDirectory(Path.GetDirectoryName(filePath));

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return Ok(new {name=file.FileName, url = "/UploadedFiles/" + file.FileName });
        }

        /// <summary>
        /// 生成条码
        /// </summary>
        /// <returns></returns>
        /// DDBH000001
        [HttpGet("BatchNo")]
        public string BatchNo(string prefix, int length)
        {
            return "";
        }

        /// <summary>
        /// 根据字典项enCode查询字典项数据
        /// </summary>
        /// <param name="enCode"></param>
        /// <returns></returns>
        [HttpGet("GetDictionaryData")]
        public async Task<dynamic> GetDictionaryData(string enCode)
        {
            //字典类型关联字典data表查询字典类型的fullname的数据
            var data = await _Db.Queryable<DictionaryTypeEntity, DictionaryDataEntity>((a, b) => new object[] { JoinType.Left, a.Id == b.DictionaryTypeId }).Where((a,b)=>a.EnCode.Contains(enCode)).Select((a, b) => new
            {
                b.EnCode,
                b.FullName
            }).ToListAsync();
            return data;
        }
    }
}
